package com.tongtong.middleware.blockchain.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.tongtong.middleware.blockchain.entity.TblAssetExtEntity;
import com.tongtong.share.client.ShareClient;

import lombok.extern.slf4j.Slf4j;
import xyz.xtt.common.response.ApiResult;

@Service
@Slf4j
public class MetadataService {
	@Autowired
	private ShareClient shareClient;
	@Autowired
	TblAssetExtService tblAssetExtService;

	public String metadataByTokenId(String tokenId) {
		TblAssetExtEntity tblAssetExtEntity = tblAssetExtService.findByTokenId(tokenId);
		if (tblAssetExtEntity.getMetadata() == null) {
			return "";
		}
		byte[] bytes = tblAssetExtEntity.getMetadata().getBytes(StandardCharsets.UTF_8);
		// 将字节数组包装成 ByteArrayInputStream
		InputStream inputStream = new ByteArrayInputStream(bytes);
		MultipartFile multipartFile;
		try {
			multipartFile = new MockMultipartFile("file", "meta.json", "application/json", inputStream);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		// 上传meta信息到oss，获取url
		String accessURL = "metadata/" + tokenId + ".json";
		ApiResult<String> uploadByAccessURL = shareClient.uploadByAccessURL(multipartFile, accessURL);
		return uploadByAccessURL.getData();
	}
}
